#include "Layer.h"

Layer::Layer(uint layerId, int _scroll_factor) :
    viewport(*(Viewport::get_instance())),
    spritelist(*(SpriteList::get_instance())),
    m_bVisible(true)
{
    m_layerId = layerId;
    surface = SDL_CreateRGBSurface(SDL_SRCCOLORKEY, viewport.width,
        viewport.height, viewport.pixelformat()->BitsPerPixel,
        viewport.pixelformat()->Rmask,
        viewport.pixelformat()->Gmask,
        viewport.pixelformat()->Bmask,
        viewport.pixelformat()->Amask);

    if (surface == NULL) {
        throw runtime_error("Layer::Layer() - Unable to load surface. "
                "  Description: " + std::string(SDL_GetError()));
    }

    SDL_SetColorKey(surface, SDL_SRCCOLORKEY, viewport.colorkey);
    if (Debug::test(DEBUG_CREATE_DELETE)) {
        cout << "layer created" << endl;
    }
}

Layer::~Layer()
{
    clear();
    if (Debug::test(DEBUG_CREATE_DELETE)) {
        cout << "layer Deleted" << endl;
    }
}

void Layer::execute() {
    render();
}

void Layer::render() {
    if (Debug::test(DEBUG_THREAD)) {
        cout << "rendering started" << endl;
    }
    SDL_FillRect(surface, NULL, viewport.colorkey);
    spriteInstanceList.draw(surface);
    if (Debug::test(DEBUG_THREAD)) {
        cout << "rendering finished" << endl;
    }
}

bool Layer::add(uint imgId, uint spriteId, SDL_Rect rect, bool visible, bool solid)
{
    return spriteInstanceList.add(imgId, spriteId, rect, visible, solid);
}

bool Layer::makeSpriteAtXYActive(int x, int y)
{
    if (Debug::test(DEBUG_INFO))
    {
        cout << "Layer " << m_layerId << " ::makeSpriteAtXYActive going to make sprite at " << x << " " << y << " active" << endl;
    }
    return spriteInstanceList.makeSpriteAtXYActive(x, y);
}

void Layer::moveActiveSpritebyXY(Sint16 x, Sint16 y)
{
    spriteInstanceList.moveActiveSpritebyXY(x, y);
}

bool Layer::activeSpriteSendToBack()
{
    return spriteInstanceList.activeSpriteSendToBack();
}

bool Layer::activeSpriteBringToFront()
{
    return spriteInstanceList.activeSpriteBringToFront();
}

bool Layer::activeSpriteToggleSolid()
{
    return spriteInstanceList.activeSpriteToggleSolid();
}

bool Layer::activeSpriteToggleVisible()
{
    return spriteInstanceList.activeSpriteToggleVisible();
}

bool Layer::activeSpriteDelete()
{
    return spriteInstanceList.activeSpriteDelete();
}
